<template>
  <div>
    <a-input @click="showSelectSection" :placeholder="placeholder" :disabled="disabled" v-model="showValue" select-model="single" readOnly>
      <a-icon slot="suffix" type="down-circle" />
    </a-input>
    <ant-modal modalWidth="900" modalHeight="500" :visible="open" modal-title="版块数据" :adjust-size="true" @cancel="cancel">
      <a-row slot="content">
        <a-col :span="12">
          <!-- 条件搜索 -->
          <div class="table-page-search-wrapper" v-hasPermi="['platform:region:add']">
            <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="regionQueryForm">
              <a-row :gutter="32">
                <a-col :span="12">
                  <a-form-item>
                    <a-input v-model="regionQueryParam.name" placeholder="请输入地区名称" allow-clear @keyup.enter.native="regionHandleQuery" />
                  </a-form-item>
                </a-col>
                <a-col>
                  <span class="table-page-search-submitButtons" style="float: right">
                    <a-button type="primary" @click="regionHandleQuery"><a-icon type="search" />查询</a-button>
                    <a-button style="margin-left: 8px" @click="resetRegionQuery"><a-icon type="redo" />重置</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-card :bordered="false">
            <a-table
              :pagination="{
                current: regionQueryParam.pageNum,
                pageSize: regionQueryParam.pageSize,
                total: regionTotal,
                showSizeChanger: true,
                showLessItems: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
                onChange: regionChangeSize,
                onShowSizeChange: onShowSectionSizeChange
              }"
              tableKey="base-region-index-table"
              @change="handleRegionTableChange"
              rowKey="id"
              size="middle"
              @refresh="getRegionList"
              :columns="regionColumns"
              :data-source="regionList"
              :loading="loading"
              :format-conditions="true"
              :row-selection="{ selectedRowKeys: selectedRegionRowKeys, onChange: onSelectRegionChange, type: 'radio' }"
              :scroll="{ x: 300 }"
            >
              <span slot="status" slot-scope="text, record">
                <a-badge :status="statusBage(record.status)" :text="statusFormat(record)" />
              </span>
            </a-table>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card :bordered="false">
            <a-table
              :pagination="{
                current: sectionQueryParam.pageNum,
                pageSize: sectionQueryParam.pageSize,
                total: sectionTotal,
                showSizeChanger: true,
                showLessItems: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
                onChange: sectionChangeSize,
                onShowSizeChange: onShowSectionSizeChange
              }"
              tableKey="base-section-index-table"
              @change="handleSectionTableChange"
              rowKey="id"
              size="middle"
              @refresh="getSectionList"
              :columns="sectionColumns"
              :data-source="sectionList"
              :loading="sectionLoading"
              :format-conditions="true"
              :row-selection="{ selectedRowKeys: selectedSectionRowKeys, onChange: onSelectSectionChange, type: 'radio' }"
            >
              <span slot="operation" slot-scope="text, record">
                <a @click="handleChange(record)"> 选择 </a>
              </span>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
      <template slot="footer">
        <a-button :disabled="disabled" @click="cancel"> 取消 </a-button>
        <a-button v-if="showValue !== '' ? true : false" type="primary" :disabled="disabled" @click="cancelSelct"> 取消选择 </a-button>
      </template>
    </ant-modal>
  </div>
</template>

<script>
import AntModal from '@/components/pt/dialog/AntModal'
import { listRegion, getInitData } from '@/api/platform/region'
import { listSection, getSection } from '@/api/platform/section'
export default {
  name: 'SelectSection',
  components: {
    AntModal
  },
  props: {
    placeholder: {
      type: String,
      default: '请选择'
    },
    // 返回数据
    value: {
      type: Object,
      required: false,
      default() {
        return {
          regionId: undefined,
          sectionId: undefined
        }
      }
    },
    disabled: {
      type: Boolean,
      requird: false,
      default: false
    },
    status: {
      type: String,
      requird: false,
      default: undefined
    }
  },
  data() {
    return {
      showValue: '',
      open: false,
      // 遮罩层
      loading: true,
      sectionLoading: true,
      // 地区表表格数据
      regionList: [],
      sectionList: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRegionRowKeys: [],
      selectedSectionRowKeys: [],
      // 地区状态字典
      statusOptions: [],
      // 选中的数据集合
      selectedRegionRows: [],
      selectedSectionRows: [],
      // 总条数
      regionTotal: 0,
      sectionTotal: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 查询参数
      regionQueryParam: {
        pageNum: 1,
        pageSize: 10,
        status: this.status,
        name: undefined
      },
      sectionQueryParam: {
        pageNum: 1,
        pageSize: 10,
        regionId: undefined
      },
      regionColumns: [
        {
          title: '地区名称',
          dataIndex: 'name',
          ellipsis: true,
          align: 'left',
          width: '150px'
        },
        {
          title: '地区编码',
          dataIndex: 'code',
          ellipsis: true,
          align: 'left',
          width: '80px'
        },
        {
          title: '地区简称',
          dataIndex: 'abbreviation',
          ellipsis: true,
          align: 'left',
          width: '100px'
        },
        {
          title: '状态',
          dataIndex: 'status',
          ellipsis: true,
          align: 'left',
          width: '100px',
          scopedSlots: { customRender: 'status' },
          fixed: 'right'
        }
      ],
      sectionColumns: [
        {
          title: '版块名称',
          dataIndex: 'name',
          ellipsis: true,
          align: 'center',
          width: '30%'
        },
        {
          title: '版块编码',
          dataIndex: 'code',
          ellipsis: true,
          align: 'center',
          width: '20%'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: '30%',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  mounted() {},
  watch: {
    ids: {
      handler(newVal, oldVal) {
        this.sectionQueryParam.regionId = newVal[0]
        this.getSectionList()
      }
    },
    value: {
      deep: true,
      handler(newVal, oldVal) {
        if (!newVal.sectionId) {
          this.selectedSectionRowKeys = []
          this.showValue = ''
        }
      }
    }
  },
  created() {
    this.getRegionList()
    getInitData('region_status').then(response => {
      this.statusOptions = response.data.region_status
    })
  },
  methods: {
    cancelSelct() {
      this.showValue = ''
      this.selectedSectionRowKeys = []
      this.$emit('change', {})
      this.open = false
    },
    handleChange(value) {
      this.selectedSectionRowKeys = []
      this.showValue = value.name
      this.selectedSectionRowKeys.push(value.id)
      this.$emit('change', { regionId: this.ids[0], sectionId: value.id })
      this.open = false
    },
    handleRegionTableChange(pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.regionQueryParam.orderByColumn = 'a.' + sorter.field
        this.regionQueryParam.isAsc = sorter.order
      }
      this.getRegionList()
    },

    handleSectionTableChange(pagination, filters, sorter) {
      if (sorter.field !== undefined && sorter.field !== null && sorter.field !== '') {
        this.sectionQueryParam.orderByColumn = 'a.' + sorter.field
        this.sectionQueryParam.isAsc = sorter.order
      }
      this.getSectionList()
    },
    /** 翻页操作 */
    onSelectRegionChange(selectedRowKeys, selectedRows) {
      this.selectedRegionRowKeys = selectedRowKeys
      this.selectedRegionRows = selectedRows
      this.ids = this.selectedRegionRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    onSelectSectionChange(selectedRowKeys, selectedRows) {
      this.selectedSetionRows = selectedRows
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },

    // 地区状态字典翻译
    statusFormat(row) {
      if (row.status) {
        return this.selectDictLabel(this.statusOptions, row.status)
      } else {
        return ''
      }
    },
    // 地区状态徽标数类型
    statusBage(status) {
      if (status === '0') {
        return 'default'
      } else if (status === '1') {
        return 'warning'
      } else if (status === '2') {
        return 'processing'
      } else if (status === '3') {
        return 'error'
      }
    },

    /** 翻页操作 */
    onShowRegionSizeChange(current, pageSize) {
      this.regionQueryParam.pageSize = pageSize
      this.getRegionList()
    },
    onShowSectionSizeChange(current, pageSize) {
      this.sectionQueryParam.pageSize = pageSize
      this.getSectionList()
    },
    /** 翻页操作 */
    regionChangeSize(current, pageSize) {
      this.regionQueryParam.pageNum = current
      this.regionQueryParam.pageSize = pageSize
      this.getRegionList()
    },
    sectionChangeSize(current, pageSize) {
      this.sectionQueryParam.pageNum = current
      this.sectionQueryParam.pageSize = pageSize
      this.getSectionList()
    },

    /** 重置按钮操作 */
    resetRegionQuery() {
      this.regionQueryParam = {
        pageNum: 1,
        pageSize: 10,
        status: this.status,
        name: undefined
      }
      this.regionHandleQuery()
    },
    setShowValue() {
      this.selectedSectionRowKeys.push(this.value.sectionId)
      getSection(this.value.sectionId).then(response => {
        this.showValue = response.data.name
      })
      this.selectedRegionRowKeys.push(this.value.regionId)
    },
    /** 查询地区表列表 */
    getRegionList() {
      this.loading = true
      this.selectedRegionRowKeys = []
      this.regionList = []
      listRegion(this.regionQueryParam).then(response => {
        this.regionList = response.data.rows
        this.regionTotal = response.data.total
        if (!this.value.sectionId) {
          this.selectedRegionRowKeys.push(this.regionList[0].id)
          this.ids.push(this.regionList[0].id)
        } else {
          this.sectionQueryParam.regionId = this.value.regionId
          this.getSectionList()
          this.setShowValue()
        }
        this.loading = false
      })
    },
    /** 查询版块管理列表 */
    getSectionList() {
      this.sectionLoading = true
      this.selectedSectionRowKeys = []
      this.sectionList = []
      listSection(this.sectionQueryParam).then(response => {
        this.sectionList = response.data.rows
        this.sectionTotal = response.data.total
        this.sectionLoading = false
      })
    },
    showSelectSection() {
      this.open = true
      this.getRegionList()
    },
    /** 搜索按钮操作 */
    regionHandleQuery() {
      this.regionQueryParam.pageNum = 1
      this.getRegionList()
    },
    cancel(e) {
      this.open = false
    }
  },
  model: { prop: 'value', event: 'change' }
}
</script>

<style lang="scss" scoped></style>
